package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionServlet extends BaseServlet{


    //往Session域中保存数据
    protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().setAttribute("key1","value1");
        resp.getWriter().write("已经向Session中保存了数据");
    }
    //获取Session域中的数据
    protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object key1 = req.getSession().getAttribute("key1");
        resp.getWriter().write("从Session中获取出key1的数据是："+key1);
    }

    protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建和获取Session会话对象
        HttpSession session = req.getSession();
        //判断当前Session是否是新创建出来的
        boolean isNew = session.isNew();
        //获取Session会话的唯一标识ID
        String id = session.getId();

        resp.getWriter().write("得到的Session，他的id是"+id+"<br/>");
        resp.getWriter().write("这个Session是否是新创建的"+isNew);
    }


    protected void defaultLift(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取了Session的默认超时市时常
        int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
        resp.getWriter().write("Session的默认超时时常为："+maxInactiveInterval+"秒");
        //Session的默认超时时常为：1800秒
    }

    //设置Session超时时长
    protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先获取 Session 对象
        HttpSession session = req.getSession();
        // 设置当前 Session3 秒后超时
        session.setMaxInactiveInterval(3);
        resp.getWriter().write("当前 Session 已经设置为 3 秒后超时");
    }

    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //让Session会话马上超时
        HttpSession session = req.getSession();
        session.invalidate();
        resp.getWriter().write("Session已经设置为超时");
    }
}
